package com.gogowan.agroenterprise.storage;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;
import android.widget.Toast;

import com.gogowan.agroenterprise.MyApplication;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.ResultInfo;
import com.gogowan.agroenterprise.model.StoreListResult;
import com.gogowan.agroenterprise.model.StoreModel;
import com.gogowan.agroenterprise.model.StoreRequest;
import com.gogowan.agroenterprise.model.UserType;
import com.gogowan.agroenterprise.utils.PinyinComparator;
import com.gogowan.agroenterprise.utils.Utils;
import com.gogowan.agroenterprise.widget.SideBar;
import com.gogowan.agroenterprise.widget.SideBar.OnTouchingLetterChangedListener;
import com.gogowan.agroenterprise.widget.SlideListView;
import com.gogowan.agroenterprise.widget.adapter.SlideBaseAdapter;
import com.gogowan.agroenterprise.widget.adapter.SlideViewHolder;
import com.gogowan.agroenterprise.widget.adapter.WarehouseListAdapter;

/**
 * 仓库管理列表界面
 * 
 * @author tjh 2017-01-03
 *
 */
public class WarehouseListActivity extends Activity implements
		View.OnClickListener {
	private ProgressDialog progressDialog;
	private SlideListView lvcountryListView;
	private WarehouseListAdapter warehouseListAdapter;
	private TextView dialogText;
	private EditText searchEdit;
	private SideBar sideBar;
	

	private List<StoreModel> sourceDateList = new ArrayList<StoreModel>();
	private List<StoreModel> sourceDateList2 = new ArrayList<StoreModel>();
	private ListBaseAdapter mListAdapter = null;
	private Handler myHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				mListAdapter.notifyDataSetChanged();
				break;
			case 1:
				// sourceDateList = filledData();
				// 根据a-z进行排序源数据
				Collections.sort(sourceDateList, new PinyinComparator());
				String[] zimu = { "A", "B", "C", "D", "E", "F", "G", "H", "I",
						"J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
						"U", "V", "W", "X", "Y", "Z", "#" };

				for (int i = 0; i < zimu.length; i++) {
					for (int x = 0; x < sourceDateList.size(); x++) {
						String iii = sourceDateList.get(x).getEnglishName()
								.substring(0, 1).toUpperCase();
						if (iii.equals(zimu[i])) {
							StoreModel storeModel = new StoreModel();
							storeModel.setEnglishName(zimu[i] + "first");
							sourceDateList.add(x, storeModel);
							break;
						}
					}
				}
				mListAdapter.notifyDataSetChanged();
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_warehouse_list);

		initView();
		initValue();
	}

	/**
	 * 初始化界面
	 */
	private void initView() {
		lvcountryListView = (SlideListView) findViewById(R.id.warehouse_list_lvcountry);
		dialogText = (TextView) findViewById(R.id.warehouse_list_dialog);
		sideBar = (SideBar) findViewById(R.id.warehouse_list_sidrbar);
		sideBar.setTextView(dialogText);

		// 设置右侧触摸监听
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				// 该字母首次出现的位置
				int position = mListAdapter.getPositionForSection(s.charAt(0));
				if (position != -1) {
					lvcountryListView.setSelection(position);
				}
			}
		});

		mListAdapter = new ListBaseAdapter(this, sourceDateList,
				R.layout.activity_warehouse_list_item, R.layout.slide_content);
		lvcountryListView.setAdapter(mListAdapter);

		lvcountryListView
				.setOnSlideItemClickListener(new SlideListView.OnSlideItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						// TODO Auto-generated method stub
						if (sourceDateList.get(position).getEnglishName()
								.indexOf("first") == -1) {
							Intent intent = new Intent(
									WarehouseListActivity.this,
									WarehouseInfoActivity.class);
							intent.putExtra("storeid",
									sourceDateList.get(position).getStoreID());
							intent.putExtra("storenaem",
									sourceDateList.get(position).getStoreName());
							WarehouseListActivity.this.startActivityForResult(
									intent, 200);
						}
					}
				});

		TextView tjText = (TextView) findViewById(R.id.warehouse_list_tj_btn);
		ImageButton fhText = (ImageButton) findViewById(R.id.warehouse_list_fh_btn);
		tjText.setOnClickListener(this);
		fhText.setOnClickListener(this);
		Button seachBtn = (Button) findViewById(R.id.warehouse_list_search_btn);
		seachBtn.setOnClickListener(this);

		searchEdit = (EditText) findViewById(R.id.warehouse_list_search_edit);
	}

	/**
	 * 初始化数据
	 */
	private void initValue() {


		progressDialog = ProgressDialog.show(WarehouseListActivity.this,
				getString(R.string.alert_title),
				getString(R.string.alert_message), true, false);

		StoreRequest storeRequest = new StoreRequest();
		// 1企业；2经销商
		if (MyApplication.mSettings.getInt("usertype",0)== UserType._GONG_CHANG.getTypeID()) {
//			storeRequest.setEnterpriseID(loginResultInfo.getEnterpriseinfo()
//					.getEnterpriseid());
		} else if (MyApplication.mSettings.getInt("usertype",0)== UserType._JING_XIAO_SHANG.getTypeID()) {
//			storeRequest.setDealerID(loginResultInfo.getEnterpriseinfo()
//					.getDealerId());
		}
//		storeRequest.setUserType(loginResultInfo.getEnterpriseinfo()
//				.getUserType());
		storeRequest.setUserID(MyApplication.mSettings.getLong("personid",0));
		storeRequest.setPageIndex(1);
		storeRequest.setType(1);

		GetWarehouseListAsyn getWarehouseListAsyn = new GetWarehouseListAsyn();
		getWarehouseListAsyn.execute(storeRequest);

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.warehouse_list_tj_btn:
			// 添加
			Intent intent = new Intent(WarehouseListActivity.this,
					WarehouseAddActivity.class);
			WarehouseListActivity.this.startActivityForResult(intent, 100);
			break;
		case R.id.warehouse_list_fh_btn:
			// 返回
			this.finish();
			break;
		case R.id.warehouse_list_search_btn:
			// 搜索
			if (TextUtils.isEmpty(searchEdit.getText())) {
				initValue();
			} else {
				sourceDateList.clear();
				for (int i = 0; i < sourceDateList2.size(); i++) {
					if (sourceDateList2.get(i).getStoreName()
							.indexOf(searchEdit.getText() + "") != -1) {
						sourceDateList.add(sourceDateList2.get(i));
					}
				}
				myHandler.sendEmptyMessage(1);
			}

			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(searchEdit.getWindowToken(), 0); // 强制隐藏键盘
			break;
		default:
			break;
		}
	}

	/**
	 * list Adapter
	 */
	private class ListBaseAdapter extends SlideBaseAdapter<StoreModel>
			implements SectionIndexer {

		private List<StoreModel> dataList;

		public ListBaseAdapter(Context context, List<StoreModel> dataList,
				int itemLayoutId, int slideLayoutId) {
			super(context, dataList, itemLayoutId, slideLayoutId);
			this.dataList = dataList;
		}

		@Override
		public void convert(SlideViewHolder holder, StoreModel bean,
				int position) {

			TextView tvLetter = holder
					.getView(R.id.warehouse_list_item_catalog);
			TextView tvTitle = holder.getView(R.id.warehouse_list_item_title);
			LinearLayout tvLetterLinear = holder
					.getView(R.id.warehouse_list_item_catalog_linear);
			LinearLayout tvTitleLinear = holder
					.getView(R.id.warehouse_list_item_title_linear);

			Button deleteButton = holder.getView(R.id.deleteButton);
			deleteButton.setOnClickListener(new ButtonClickListener(position));

			if (bean.getEnglishName().indexOf("first") == -1) {
				tvLetterLinear.setVisibility(View.GONE);
				tvTitleLinear.setVisibility(View.VISIBLE);
				tvTitle.setText(bean.getStoreName());
				holder.getConvertView().setCanLeftSlide(true);
			} else {
				tvLetterLinear.setVisibility(View.VISIBLE);
				tvTitleLinear.setVisibility(View.GONE);
				tvLetter.setText(bean.getEnglishName().subSequence(0, 1));
				holder.getConvertView().setCanLeftSlide(false);
			}

		}

		class ButtonClickListener implements OnClickListener {

			private int position = 0;

			public ButtonClickListener(int position) {
				this.position = position;
			}

			@Override
			public void onClick(View v) {
				switch (v.getId()) {
				case R.id.deleteButton:
					// 侧滑删除
					progressDialog = ProgressDialog.show(
							WarehouseListActivity.this,
							getString(R.string.alert_title),
							getString(R.string.alert_message), true, false);

					StoreModel storeModel = new StoreModel();
					// 1企业；2经销商
//					storeModel.setEnterprise_Info_ID(loginResultInfo
//							.getEnterpriseinfo().getEnterpriseid());
//					storeModel.setDealerID(loginResultInfo.getEnterpriseinfo()
//							.getDealerId());
					storeModel.setStoreID(sourceDateList.get(position)
							.getStoreID());
//					storeModel.setUserType(loginResultInfo.getEnterpriseinfo()
//							.getUserType());
					storeModel.setType(1);

					DelWarehouseListAsyn delWarehouseListAsyn = new DelWarehouseListAsyn(
							position);
					delWarehouseListAsyn.execute(storeModel);
					break;
				}
			}
		}

		@Override
		public Object[] getSections() {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public int getSectionForPosition(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public int getPositionForSection(int sectionIndex) {
			// TODO Auto-generated method stub
			for (int i = 0; i < getCount(); i++) {
				String sortStr = dataList.get(i).getEnglishName();
				char firstChar = sortStr.toUpperCase().charAt(0);
				if (firstChar == sectionIndex) {
					return i;
				}
			}
			return -1;
		}

	}

	/**
	 * 为sourceDateList填充数据
	 * 
	 * @return
	 */
	// private List<SortModel> filledData() {
	//
	// List<SortModel> mSortList = new ArrayList<SortModel>();
	// String[] arrss = { "啊", "请", "我", "饿", "人", "图", "有", "哦", "盘", "是",
	// "哎哎", "的", "到", "发", "个", "和", "就", "可", "了", "在", "箱", "从",
	// "不", "你", "码", "1", "123", "we", "t", "?", "~" };
	//
	// HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
	// defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
	// defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
	//
	// SortModel sortModel;
	//
	// for (int i = 0; i < arrss.length; i++) {
	// sortModel = new SortModel();
	// sortModel.setName(arrss[i]);
	// String pinyinName = "";
	// char[] nameChar = arrss[i].toCharArray();
	//
	// try {
	// pinyinName = PinyinHelper.toHanyuPinyinStringArray(nameChar[0],
	// defaultFormat)[0].charAt(0) + "";
	// sortModel.setSortLetters(pinyinName);
	// } catch (Exception e) {
	// // TODO: handle exception
	// sortModel.setSortLetters("#");
	// }
	//
	// mSortList.add(sortModel);
	// }
	//
	// return mSortList;
	// }

	/**
	 * 获取仓库列表
	 * 
	 * @author tjh
	 *
	 */
	private class GetWarehouseListAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(WarehouseListActivity.this,
						getString(R.string.server_error), Toast.LENGTH_LONG)
						.show();
			} else {
				com.gogowan.agroenterprise.model.Message message = (com.gogowan.agroenterprise.model.Message) Utils
						.fromJSON((String) res,
								com.gogowan.agroenterprise.model.Message.class);
				String string = Utils.getMessageContent(message);

				if (string == null || string.equals("")) {
					Toast.makeText(WarehouseListActivity.this,
							getString(R.string.analyse_error),
							Toast.LENGTH_LONG).show();
				} else {
					StoreListResult storeListResult = (StoreListResult) Utils
							.fromJSON(string, StoreListResult.class);
					sourceDateList.clear();
					sourceDateList2.clear();
					if (storeListResult.getResult() == 21000) {
						sourceDateList.addAll(storeListResult.getStoreList());
						sourceDateList2.addAll(storeListResult.getStoreList());
						for (int i = 0; i < sourceDateList.size(); i++) {
							if (TextUtils.isEmpty(sourceDateList.get(i)
									.getEnglishName())) {
								sourceDateList.get(i).setEnglishName("#");
							}
						}
						myHandler.sendEmptyMessage(1);
					} else {
						Toast.makeText(WarehouseListActivity.this,
								storeListResult.getResultinfo(),
								Toast.LENGTH_LONG).show();
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			StoreRequest storeRequest = (StoreRequest) params[0];
			String json = Utils.toJSON(storeRequest);
			com.gogowan.agroenterprise.model.Message message = new com.gogowan.agroenterprise.model.Message(
					21000, true, json);
			// String ss = Utils.toJSON(message);
			// Log.i("gggggggggggggggggg===", ss);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}

	}

	/**
	 * 删除仓库
	 * 
	 * @author tjh
	 *
	 */
	private class DelWarehouseListAsyn extends MyAsyncTask {
		private int position;

		public DelWarehouseListAsyn(int position) {
			this.position = position;
		}

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(WarehouseListActivity.this,
						getString(R.string.server_error), Toast.LENGTH_LONG)
						.show();
			} else {
				com.gogowan.agroenterprise.model.Message message = (com.gogowan.agroenterprise.model.Message) Utils
						.fromJSON((String) res,
								com.gogowan.agroenterprise.model.Message.class);
				String string = Utils.getMessageContent(message);

				if (string == null || string.equals("")) {
					Toast.makeText(WarehouseListActivity.this,
							getString(R.string.analyse_error),
							Toast.LENGTH_LONG).show();
				} else {
					ResultInfo resultInfo = (ResultInfo) Utils.fromJSON(string,
							ResultInfo.class);
					if (resultInfo.getResult() == 21300) {
						String szmStr = sourceDateList.get(position)
								.getEnglishName().substring(0, 1);
						int szmSize = 0;
						for (int i = 0; i < sourceDateList.size(); i++) {
							if (sourceDateList.get(i).getEnglishName()
									.substring(0, 1).equals(szmStr)) {
								szmSize++;
							}
						}

						sourceDateList.remove(position);
						sourceDateList2.remove(position);
						if (szmSize <= 2) {
							sourceDateList.remove(position - 1);
						}

						myHandler.sendEmptyMessage(0);
					} else {
						Toast.makeText(WarehouseListActivity.this,
								resultInfo.getResultinfo(), Toast.LENGTH_LONG)
								.show();
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			StoreModel storeModel = (StoreModel) params[0];
			String json = Utils.toJSON(storeModel);
			com.gogowan.agroenterprise.model.Message message = new com.gogowan.agroenterprise.model.Message(
					21300, true, json);
			String ss = Utils.toJSON(message);
			Log.i("gggggggggggggggggg===", ss);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case 100:
				// 仓库添加成功刷新列表
				initValue();
				break;
			case 200:
				// 数据修改刷新列表
				initValue();
				break;
			}
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		lvcountryListView = null;
		warehouseListAdapter = null;
		sideBar = null;
		sourceDateList.clear();
		sourceDateList = null;
	}
}
